<?php

namespace App\Repositories;

use App\User;

class WechatLoginRepository
{
    /**
     * 尝试进行base登录
     *
     * @param $unionid
     * @return mixed
     */
    public function attemptBaseLogin($unionid)
    {
        $user = User::where('unionid', $unionid)->first();

        return $user;
    }

    /**
     * 当base登录失败后，尝试userinfo登录，其实就是新建一个用户并返回
     *
     * @param $user
     * @return mixed
     */
    public function attemptUserinfoLogin($user)
    {
        $attemptUser = $this->attemptBaseLogin($user->original['unionid']);
        if ($attemptUser) {
            return $attemptUser;
        }

        $sexArr = [
            0 => '',
            1 => '男',
            2 => '女'
        ];

        $createUser = User::create([
            'name'     => $user->name,
            'nickname' => $user->nickname,
            'avatar'   => $user->avatar,
            'sex'      => $sexArr[intval($user->sex)],
            'unionid'  => $user->original['unionid']
        ]);

        return $createUser;
    }
}
